//获取应用实例
const app = getApp();
const common = require("../../../../utils/common.js");
const utils = require("../../../../utils/util.js");

import { $wuxToast } from "../../../../miniprogram_npm/weapp/index.js";

Page({
  data: {
    lock:false,
    productNo:'', // 货号
    plate_tasts:[], // 物料bom 表格数据
    material_id: 0,
    current: "tab1",
    /***********************************阿尔法*******************************/
    //物料类型 
    material_meta_data: [
      {
        value: "01",
        label: "正常物料",
      },
      {
        value: "03",
        label: "推荐物料",
      },
      {
        value: "02",
        label: "开发物料",
      },
    ],

    //阿尔法表单数据
    alphaFormData: {
      isSynCtegoryUnit: 1,
      list: [],  
      storeTypeIndex: 0,
      baseUnitIndex: '',
      id: "", 
      /**
       * list[].skuList orderData 下面的
       * confirm_num 下单数量  dead_line
       */ 
      /**示例数据 */
      // materialName: "物料名称1111",
      /**示例数据 */
    }, 
    //物料分类
    materialCategoryTreeIndexArr: [],
    materialCategoryTree: [],
    materialCategoryMeta: [], 
    //年份
    defaultYearIndex: 0,
    yearArray: [], 
    //季节
    defaultSeasonIndex: 0,
    seasonList: [
      {
        label: "春",
        value: "C",
      },
      {
        label: "夏",
        value: "X",
      },
      {
        label: "秋",
        value: "Q",
      },
      {
        label: "冬",
        value: "D",
      },
      {
        label: "通用",
        value: "T",
      },
    ], 
    //状态
    defaultStatusIndex: 0,
    statusList: [
      {
        label: "启用",
        value: 1,
      },
      {
        label: "禁用",
        value: 0,
      },
    ],

    //是否工艺底料
    defaultWorkIndex: 0,
    workList: [
      {
        label: "否",
        value: 0,
      },
      {
        label: "是",
        value: 1,
      },
    ],

    //供货方式
    outsourceTypeIndex: 0,
    outsourceTypeList: [
      {
        label: "自采-销售",
        value: 1,
      },
      {
        label: "自采-调拨",
        value: 2,
      },
      {
        label: "委外-指定供应商",
        value: 3,
      },
      {
        label: "委外-建议供应商",
        value: 4,
      },
      {
        label: "委外-供应商无限制",
        value: 5,
      },
    ],

    //是否弹出
    isShowPopup: false, 
    //供应商
    defaultFieldNames: {
      label: "supplierShortName",
      value: "supplierId",
    },
    defaultFieldNames2: {
      label: "supplierShortName",
      value: "id",
    },
    search_keyword: "",
    supplyList: [],
    // sel_supply_ids: [],
    current_supplyid: "",
    materialColorList: [], // 物料sku列表
    materialUnitList: [],
    materialUnitList2: [],
    // ***************** 绑定物料相关 *************** 
    create_bom_show:false,

    show_bom_screen: false, // 遮罩-绑定用量
 
    // 添加bom formData
    abmFormData: { 
        mateCate: [],   // 分类 abmFormData.mateCate
        colorId: "", // 颜色
        mateName: "", // 名称
        baseUnitIndex: '', // 用量
        loss: "", // 损耗 
    }, 
     
    abmMateCateMeta:[], // 分类tree-原数据 （为了不影响原来的分类tree）
    abmMateCateIdxArr:[], // 分类tree-选择的ID
    lossTreeData:[], // 损耗tree-data
    lossTree:[], // 损耗tree
    selectStrArr:{
        loss:'', // 损耗名称
        mateItemType:'', // 物料项目类型
    },

    
    
    /***********************************阿尔法*******************************/
  },

  /********************************************************阿尔法***************************************************************/
  onShow() {
    this.getList();
    this.getSupplyList()
  },

  onLoad: function (options) {
    // 设置标题
    wx.setNavigationBarTitle({
      title: "创建物料档案",
    });
    console.log("onLoad-创建物料档案-货号",options.productNo)
    let lossTree = [] // 损耗选项
    let lossTreeData = [] // 损耗选项
    // 从 0 到 25 
    for(let li = 0;li<26;li++){
        lossTreeData.push({
            "name": li+"%",
            "value": li,
        })
        lossTree.push(li+"%")
    } 
    this.setData({
      productNo: options.productNo, // 货号 
      lossTree: lossTree,
      lossTreeData: lossTreeData,
    }); 
    // 生成年份
    common.generateYearArray((yearArray, defaultIndex) => { 
      this.setData({
        yearArray: yearArray,
        defaultYearIndex: defaultIndex,
      });
    }); 
    this.get_plate_tasts(options.productNo) // 获取物料列表
    
  },
  
  firstChooseSetDataIndex(e) {
    this.setDataIndex(e);
    let { index } = e.currentTarget.dataset;
    if (
      this.data.workList[this.data.alphaFormData.list[index].firstChooseIndex]
        .value == 1
    ) {
      this.data.alphaFormData.list.forEach((v, k) => {
        if (k != index) {
          v.firstChooseIndex = 0;
        }
      });
    }
    this.setData({
      alphaFormData: this.data.alphaFormData,
    });
  },
  errmsg(msg = "") {
    $wuxToast().show({
      type: "cancel",
      duration: 1000,
      color: "#fff",
      text: msg,
      success: () => console.log("拦截提示"),
    });
  },

  //获取详情后，设置对应索引值 以 展示数据
  setMetaDataIndex() {
    let alphaFormData = this.data.alphaFormData;
    let storeTypeIndex = this.data.material_meta_data.findIndex(
      (v) => alphaFormData.storeType == v.value
    );
    alphaFormData.storeTypeIndex = storeTypeIndex == -1 ? "" : storeTypeIndex;
    
    let baseUnitIndex = this.data.materialUnitList.findIndex(
      (v) => alphaFormData.baseUnit == v.value
    );
    alphaFormData.baseUnitIndex = baseUnitIndex == -1 ? "" : baseUnitIndex;
    
    let typeIndex = this.data.materialCategoryMeta[0].findIndex(
      (v) => v.value == alphaFormData.type
    );
    this.data.materialCategoryMeta[1] =
      this.data.materialCategoryMeta[0][typeIndex].children;
    let type2Index = this.data.materialCategoryMeta[1].findIndex(
      (v) => v.value == alphaFormData.lastNode
    );
    this.data.materialCategoryTreeIndexArr = [typeIndex, type2Index];
    let defaultStatusIndex = this.data.statusList.findIndex(
      (v) => v.value == alphaFormData.materialStatus
    );
    let defaultYearIndex = this.data.yearArray.findIndex(
      (v) => v == alphaFormData.developmentYear
    );
    let defaultSeasonIndex = this.data.seasonList.findIndex(
      (v) => v.value == alphaFormData.usageSeason
    );
    let outsourceTypeIndex = this.data.outsourceTypeList.findIndex(
      (v) => v.value == alphaFormData.outsourceType
    );
    let defaultWorkIndex = this.data.workList.findIndex(
      (v) => v.value == alphaFormData.issueProcessBackingMaterial
    );

    // 设置供应商的
    alphaFormData.list.forEach((v) => {

      //设置单位换算的
      v.confirmationCoefficientDtoList.forEach((vv, kk) => {
        vv.baseUnitIndex = this.data.materialUnitList.findIndex(
          (vvv) => vvv.value == vv.baseUnit
        );
        vv.purchasingUnitIndex = this.data.materialUnitList.findIndex(
          (vvv) => vvv.value == vv.purchasingUnit
        );
      });

      v.isEnableIndex = this.data.statusList.findIndex(
        (vv) => vv.value == v.isEnable
      );
      v.firstChooseIndex = this.data.workList.findIndex(
        (vv) => vv.value == v.firstChoose
      );
      v.baseUnitIndex = this.data.materialUnitList.findIndex(
        (vv) => vv.value == v.baseUnit
      );
      v.purchaseUnitIndex = this.data.materialUnitList.findIndex(
        (vv) => vv.value == v.purchaseUnit
      );
      //设置供应商下的sku的
      v.skuList.forEach((skuitem) => {

        skuitem.attachment.file_path = `${app.globalData.alphaCdnUrl}/${skuitem.attachment.url}`;

        skuitem.colorCodeIndex = this.data.materialColorList.findIndex(
          (vv) => vv.value == skuitem.colorCode
        );

        skuitem.purchaseUnitIndex = this.data.materialUnitList2.findIndex(
          (vv) => vv.value == skuitem.purchaseUnit
        );

        skuitem.baseUnitIndex = this.data.materialUnitList2.findIndex(
          (vv) => vv.value == skuitem.baseUnit
        );
      });
    }); 
    this.setData({
      defaultWorkIndex,
      outsourceTypeIndex,
      defaultSeasonIndex,
      defaultStatusIndex,
      defaultYearIndex,
      materialCategoryTreeIndexArr: this.data.materialCategoryTreeIndexArr,
      materialCategoryMeta: this.data.materialCategoryMeta, 
      alphaFormData,
    });
  },

  // 点击添加图片时
  AddPic: function (e) {
    this.setData({
      lock:true,
    })
    const that = this;
    let { index, index2 } = e.currentTarget.dataset;
    let sku = this.data.alphaFormData.list[index].skuList[index2];
    // 选择图片
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      maxDuration: 30,
      sizeType: ["original", "compressed"],
      camera: "back",
      success(res) {
        console.log("选择的缩率图片", res);
        for (var i = 0; i < res.tempFiles.length; i++) {
          app
            .alpha_upload(res.tempFiles[i].tempFilePath)
            .then((upRes) => {
              console.log("上传图片结果upRes：", upRes);
              const arr = upRes.file_suffix.split(".");
              let upload_file = {
                file_path: upRes.file_path,
                fileName: upRes.file_key,
                fileSize: 1,
                fileType: arr[1] || "",
                url: upRes.file_key,
              };
          
              that.setData({
                [`alphaFormData.list[${index}].skuList[${index2}].attachment`]:
                  upload_file,
              });
            })
            .finally(() => {
              that.setData({
                lock:false,
              })
            });
        }
      },
    });
  },

  //设置基础信息
  setAlphaFormData() {
    //构建部分数据的value 
    if (
      this.data.alphaFormData.materialName == undefined ||
      this.data.alphaFormData.materialName == ""
    ) {
      this.errmsg("请输入物料名称");
      return;
    }
    let list = this.data.alphaFormData.list;
    if (list.length <= 0) {
      this.errmsg("至少选择一个供应商");
      return;
    }

    for (let index = 0; index < list.length; index++) {
      // 不相关硬拼参数
      list[index].keyword = "";
      list[index].bulkPrice = null;
      (list[index].isOneClickPriceModification = 0),
        (list[index].isOneClickSalePriceModification = 0),
        (list[index].plateCuttingPrice = null),
        (list[index].baseUnitText = null),
        (list[index].colorCards = []),
        (list[index].model = null),
        (list[index].isSpecifyType = false),
        (list[index].specifyType = 1),
        (list[index].confirmationCoefficient = ""),
        // (list[index].confirmationCoefficientDtoList = [
        //   {
        //     baseUnit: "01",
        //     baseUnitName: "米",
        //     purchasingUnit: "01",
        //     purchasingUnitName: "米",
        //     constId: "cg2ldbsxa2g0000",
        //     confirmationCoefficient: 1,
        //   },
        // ]),
        (list[index].netWidth = null),
        (list[index].purchaseUnit = null),
        (list[index].saleUnit = null),
        (list[index].warehousingUnit = null),
        (list[index].mainChartIndex = 0),
        (list[index].spec = null),
        (list[index].supplierSpec = null),
        (list[index].startingQuantity = null),
        (list[index].unitUse = null),
        (list[index].totalKilograms = 25),
        (list[index].singleMeter = null),
        (list[index].delete = 0);
      // 不相关硬拼参数

      let prefix = list[index].supplierShortName || "";
      if (
        list[index].supplierSpu == undefined ||
        list[index].supplierSpu == ""
      ) {
        this.errmsg(prefix + "面料款号不能为空");
        return;
      }
      if (list[index].baseUnitIndex == undefined) {
        this.errmsg(prefix + "基本单位请选择");
        return;
      }

      if (list[index].purchaseUnitIndex == undefined) {
        this.errmsg(prefix + "采购单位请选择");
        return;
      }
      list[index].baseUnit =
        this.data.materialUnitList[list[index].baseUnitIndex].value;
        list[index].purchaseUnit =
        this.data.materialUnitList[list[index].purchaseUnitIndex].value;

      list[index].firstChoose =
        this.data.workList[list[index].firstChooseIndex].value;

      list[index].isEnable =
        this.data.statusList[list[index].isEnableIndex].value;

      if (list[index].skuList == undefined || list[index].skuList.length <= 0) {
        this.errmsg(prefix + "请添加供货sku");
      }
      //构建供应商的sku数据
      for (
        let index2 = 0;
        index2 < list[index].confirmationCoefficientDtoList.length;
        index2++
      ) {
        let dto_prefix =
          (list[index].supplierShortName || "") +
          "第" +(index2 + 1) +"行换算,";
        if (
          list[index].confirmationCoefficientDtoList[index2].baseUnitIndex ==
            undefined ||
          list[index].confirmationCoefficientDtoList[index2].baseUnitIndex <
            0 ||
          list[index].confirmationCoefficientDtoList[index2]
            .purchasingUnitIndex == undefined ||
          list[index].confirmationCoefficientDtoList[index2]
            .purchasingUnitIndex < 0
        ) {
          this.errmsg(dto_prefix + "单位换算的单位不能为空");
          return;
        }

        list[index].confirmationCoefficientDtoList[index2].baseUnit =
          this.data.materialUnitList[
            list[index].confirmationCoefficientDtoList[index2].baseUnitIndex
          ].value;
        list[index].confirmationCoefficientDtoList[index2].baseUnitName =
          this.data.materialUnitList[
            list[index].confirmationCoefficientDtoList[index2].baseUnitIndex
          ].label;
        list[index].confirmationCoefficientDtoList[index2].purchasingUnit =
          this.data.materialUnitList[
            list[index].confirmationCoefficientDtoList[
              index2
            ].purchasingUnitIndex
          ].value;
        list[index].confirmationCoefficientDtoList[index2].purchasingUnitName =
          this.data.materialUnitList[
            list[index].confirmationCoefficientDtoList[
              index2
            ].purchasingUnitIndex
          ].label;
      }

      //构建供应商的sku数据
      for (let index2 = 0; index2 < list[index].skuList.length; index2++) {
        let sku_prefix =
          (list[index].supplierShortName || "") +
          "第" +
          (index2 + 1) +
          "行sku,";
        if (
          list[index].skuList[index2].colorCodeIndex == undefined ||
          list[index].skuList[index2].colorCodeIndex < 0
        ) {
          this.errmsg(sku_prefix + "请选择颜色");
          return;
        }
        if (
          list[index].skuList[index2].supplierSpec == undefined ||
          list[index].skuList[index2].supplierSpec == ""
        ) {
          this.errmsg(sku_prefix + "请输入规格/尺寸");
          return;
        }
        if (
          list[index].skuList[index2].plateCuttingPrice == undefined ||
          list[index].skuList[index2].plateCuttingPrice <= 0
        ) {
          this.errmsg(sku_prefix + "请输入采购单价");
          return;
        }
        if (
          list[index].skuList[index2].purchaseUnitIndex == undefined ||
          list[index].skuList[index2].purchaseUnitIndex < 0
        ) {
          this.errmsg(sku_prefix + "请选择采购单位");
          return;
        }
        if (
          list[index].skuList[index2].bigGoodsPrice == undefined ||
          list[index].skuList[index2].bigGoodsPrice <= 0
        ) {
          this.errmsg(sku_prefix + "请输入基本单价");
          return;
        }
        if (
          list[index].skuList[index2].baseUnitIndex == undefined ||
          list[index].skuList[index2].baseUnitIndex < 0
        ) {
          this.errmsg(sku_prefix + "请选择基本单位");
          return;
        }

        list[index].skuList[index2].colorCode =
          this.data.materialColorList[
            list[index].skuList[index2].colorCodeIndex
          ].value;

        list[index].skuList[index2].baseUnit =
          this.data.materialUnitList2[
            list[index].skuList[index2].baseUnitIndex
          ].value;
        list[index].skuList[index2].baseUnitText =
          this.data.materialUnitList2[
            list[index].skuList[index2].baseUnitIndex
          ].label;

        list[index].skuList[index2].purchaseUnit =
          this.data.materialUnitList2[
            list[index].skuList[index2].purchaseUnitIndex
          ].value;
        list[index].skuList[index2].purchaseUnitName =
          this.data.materialUnitList2[
            list[index].skuList[index2].purchaseUnitIndex
          ].label;

        list[index].skuList[index2].spec =
          list[index].skuList[index2].supplierSpec;

        list[index].skuList[index2].isMainChart = list[index].skuList[index2]
          .isMainChart
          ? 1
          : 0;
        list[index].skuList[index2].state = list[index].skuList[index2].state
          ? 1
          : 0;
      }
    }
    console.log('aaaaaaaaaaaaa',this.data.materialUnitList[this.data.alphaFormData.baseUnitIndex]
    .value)
    this.setData({
      [`alphaFormData.list`]: list,
       //物料基本单位
       [`alphaFormData.baseUnit`]:
       this.data.materialUnitList[this.data.alphaFormData.baseUnitIndex]
         .value,
         [`alphaFormData.baseUnitName`]:
         this.data.materialUnitList[this.data.alphaFormData.baseUnitIndex]
           .label,
      //物料类型
      [`alphaFormData.storeType`]:
        this.data.material_meta_data[this.data.alphaFormData.storeTypeIndex]
          .value,
      //物料分类
      [`alphaFormData.materialClassificationText`]:
        this.data.materialCategoryMeta[0][
          this.data.materialCategoryTreeIndexArr[0]
        ].label +
        "/" +
        this.data.materialCategoryMeta[1][
          this.data.materialCategoryTreeIndexArr[1]
        ].label,
      [`alphaFormData.type`]:
        this.data.materialCategoryMeta[0][
          this.data.materialCategoryTreeIndexArr[0]
        ].value,
      [`alphaFormData.firstClass`]:
        this.data.materialCategoryMeta[1][
          this.data.materialCategoryTreeIndexArr[1]
        ].value,
      [`alphaFormData.lastNode`]:
        this.data.materialCategoryMeta[1][
          this.data.materialCategoryTreeIndexArr[1]
        ].value,

      //状态
      [`alphaFormData.materialStatus`]:
        this.data.statusList[this.data.defaultStatusIndex].value,
      //是否工艺底料
      [`alphaFormData.issueProcessBackingMaterial`]:
        this.data.workList[this.data.defaultWorkIndex].value,
      //开发年份
      [`alphaFormData.developmentYear`]:
        this.data.yearArray[this.data.defaultYearIndex],

      //使用季节
      [`alphaFormData.usageSeason`]:
        this.data.seasonList[this.data.defaultSeasonIndex].value,

      //供货方式
      [`alphaFormData.outsourceType`]:
        this.data.outsourceTypeList[this.data.outsourceTypeIndex].value,

      // 不相关硬拼参数
      [`alphaFormData.categoryUnitList`]: [],
      [`alphaFormData.principalComponent`]: "",
      [`alphaFormData.elasticityAttribute`]: "",
      [`alphaFormData.isMaterialPreparation`]: "",
      [`alphaFormData.thirdClass`]: "",
      // 不相关硬拼参数
    });

    console.log("生成的：", this.data.alphaFormData);

    this.submitForm();
  },

  // 删除表格颜色  ffhh 
  delMateOrder: function (events) {
    // const index = events.currentTarget.dataset.index;
    // let mateOrders = this.data.mateOrders  
    // mateOrders.splice(index, 1); 
    // this.setData({
    //   mateOrders: mateOrders,
    // });
  },
   // 输入生产数量时
  inpMateNum: function (e) {
    let tidx = e.currentTarget.dataset.tidx; // 第一层 id
    let index = e.currentTarget.dataset.index; // 第二层 id
    
    let field = e.currentTarget.dataset.field;
    let value = e.detail.value

    console.log('tidx',tidx)
    console.log('index',index)
    console.log('field',field)
    console.log('field',e.detail.value)
    console.log('alphaFormData-list',this.data.alphaFormData.list)
    console.log('alphaFormData-skuList',this.data.alphaFormData.list[tidx].skuList[index])
   
    let alphaFormData = this.data.alphaFormData
     alphaFormData.list[tidx].skuList[index][field] = value
    //  alphaFormData[index]['sku_list'][index2][field] = e.detail.value;
    this.setData({
      alphaFormData,
    })
    // alphaFormData
    console.log('alphaFormData-结果',this.data.alphaFormData)
  },
    // 打开 - 绑定用量
    open_bom_screen(e) {

        console.log('绑定用量',e)
        // this.getTemplateBom();
        //   // th/
            this.setData({
                show_bom_screen: true,
            
                // bom_index: e.currentTarget.dataset.index,
                // bom_index2: e.currentTarget.dataset.index2,
            })
    },

    // 关闭- 绑定用量
    close_bom_screen: function (e) {
        console.log('关闭- 绑定用量')
        this.setData({
            show_bom_screen: false, 
            // is_show_choose_pro: false,
            // [`show_config.show`]: false,
        })
    },
  
    // 打开 - 绑定计划
    open_batch_select(e) { 
        console.log('绑定计划')
        // this.getTemplateBom();
        //   // th/
        //   this.setData({
        //       is_show_choose_pro: true,
        //       is_shade_screen: true,
        //       bom_index: e.currentTarget.dataset.index,
        //       bom_index2: e.currentTarget.dataset.index2,
        //   })
    },

    // 保存bom-选择物料分类
    abmCgMateCate(e) {  
        this.setData({
            abmMateCateIdxArr: e.detail.value, // 选择的值 
            // ["abmFormData.mateCate"]: materialCategoryMeta, // todo 分类
        }); 
    },

    // 保存bom-分类列改变
    abmColCgMateCate(e) {
        // abmFormData.mateCate
        let materialCategoryTree = this.data.materialCategoryTree;
        console.log("添加bom:materialCategoryTree",materialCategoryTree) 
        let abmMateCateIdxArr = this.data.abmMateCateIdxArr;
        let index = e.detail.value;
        let column = e.detail.column;
        if (column == 0) {
            abmMateCateIdxArr = [index, 0];
        }
        if (column == 1) {
            abmMateCateIdxArr[1] = index;
        } 
        // 重新获取tree 分级数组 [{"name":"一级"}],[{"name":"二级"}]   
        let abmMateCateMeta = utils.opAefMetaCateMeta(
            abmMateCateIdxArr,
            materialCategoryTree
        );  
        this.setData({
            abmMateCateIdxArr, // 选中的
            abmMateCateMeta, // 选中的 
        }); 
    },

    // 保存bom-损耗
    abmCgLoss(e) { 
        console.log("损耗")  
        let index = e.detail.value
        this.setData({
           ["abmFormData.lossVal"]: this.data.lossTreeData[index].value, // 选中的值
           ["selectStrArr.loss"]: this.data.lossTreeData[index].name // 选中的标题
           
        });
    },

    // 保存bom-损耗
    abmColCgLoss(e) { 
        
        this.setData({
            // abmMateCateIdxArr, // 选中的
            // abmMateCateMeta, // 选中的 
        });
       // console.log("添加bom:abmFormData",this.data.abmFormData) 
    },

    // saveBom 
    saveBom(e) { 
         
        // let data = {
        //     material_type: this.data.bom_form.material_type,
        //     template_id: this.data.template_id,
        //     bom_detail_id: this.data.bom_form.bom_detail_id,
        //     bom_name: this.data.bom_form.bom_name,
        //     price: this.data.bom_form.price,
        //     single_piece: this.data.bom_form.single_piece,
        // };
        // var result = app.request_api ('admin/Template/mini_save_bom', data, true, 'POST', {}, true);
        // result.then (res => {
        //     wx.showToast ({
        //         title: res.msg,
        //         icon: 'success',
        //         duration: 2000,
        //     });
        //     this.onClickHide ();
        //     this.get_template_detail ()
        // }) 
    },

  // 提交表单
  submitForm() {
    console.log("创建xx-8787")
    let data = this.data.alphaFormData;
    // 调试模式
    // common.request_api_test(
    //   "http://127.0.0.1:9091/sgsPdmPlateTask/savePurOrder",
    // 生产模式
    // common.request_api(
    //   "/api/ums/sgsPdmPlateTask/savePurOrder",

    common.request_api_test(
      "http://127.0.0.1:9091/sgsPdmPlateTask/savePurOrder",
      { ...data },
      true,
      "post"
    ).then((res) => {
      if (res.code == 200) {
        wx.showToast({
          title: res.msg,
          icon: "success",
          duration: 1500,
        });
        wx.navigateTo({
          url: "/alpha/pages/alpha_material/index",
        });
      }
    });

    // common.request_api(
    //     this.data.material_id > 0
    //       ? "/api/pdm/materialMasterData/updateMaterialMasterData"
    //       : "/api/pdm/materialMasterData/addMaterialMasterData",
    //     { ...data },
    //     true,
    //     "post"
    //   ).then((res) => {
    //     if (res.code == 200) {
    //       wx.showToast({
    //         title: res.msg,
    //         icon: "success",
    //         duration: 1500,
    //       });
    //       wx.navigateTo({
    //         url: "/alpha/pages/alpha_material/index",
    //       });
    //     }
    //   });
  },
  //获取物料单位
  getMaterialUnit() {
    common
      .request_api(
        "/api/pdm/commonDictionary/queryByGroupIdentification/unit",
        {},
        true,
        "get"
      )
      .then((res) => {
        let data2 = JSON.parse(JSON.stringify(res.data));
        for (var i = 0; i < data2.length; i++) {
          data2[i].label = "元/" + res.data[i].label;
        }
        this.setData({
          materialUnitList: res.data,
          materialUnitList2: data2,
        });
      });
  },

  //获取物料颜色
  getMaterialColor() {
    common
      .request_api(
        "/api/pdm/commonDictionary/queryByGroupIdentification/materialColor",
        {},
        true,
        "get"
      )
      .then((res) => {
        this.setData({
          materialColorList: res.data,
        });
      });
  },

  delDto(e) {
    let { index, index2 } = e.currentTarget.dataset;
    let list = this.data.alphaFormData.list;
    if (list[index].confirmationCoefficientDtoList.length == 1) {
      $wuxToast().show({
        type: "cancel",
        duration: 1000,
        color: "#fff",
        text: "至少保留一行",
        success: () => console.log("拦截提示"),
      });
      return;
    }
    list[index].confirmationCoefficientDtoList.splice(index2, 1);

    this.setData({
      ["alphaFormData.list"]: list,
    });
  },

  addDto(e) {
    let { index } = e.currentTarget.dataset;
    let confirmationCoefficientDtoList =
      this.data.alphaFormData.list[index].confirmationCoefficientDtoList;
    confirmationCoefficientDtoList.push({
      constId: "cg2ldbsxa2g0000",
      confirmationCoefficient: 1,
    });
    this.setData({
      [`alphaFormData.list[${index}].confirmationCoefficientDtoList`]:
        confirmationCoefficientDtoList,
    });
  },

  compuctSetDataIndex(e) {
    this.setDataIndex(e);
    let { index, index2 } = e.currentTarget.dataset;
    this.compuctPrice(index, index2);
  },

  //遍历sku设置
  compuctPrice(index, index2) {
    let dto =
      this.data.alphaFormData.list[index].confirmationCoefficientDtoList[
        index2
      ];
    if (dto.confirmationCoefficient > 0) {
      this.data.alphaFormData.list[index].skuList.forEach((v, k) => {
        if (
          v.purchaseUnitIndex == dto.purchasingUnitIndex &&
          v.baseUnitIndex == dto.baseUnitIndex
        ) {
          v.bigGoodsPrice = v.plateCuttingPrice * dto.confirmationCoefficient;
        }
      });
    }
    this.setData({
      [`alphaFormData.list[${index}]`]: this.data.alphaFormData.list[index],
    });
  },

  //删除sku行
  delSku(e) {
    let { index, index2 } = e.currentTarget.dataset;
    let list = this.data.alphaFormData.list;
    list[index].skuList.splice(index2, 1);
    this.setData({
      ["alphaFormData.list"]: list,
    });
  },

  //sku增加行
  addSku(e) {
    let { index } = e.currentTarget.dataset;
    let list = this.data.alphaFormData.list;
    list[index].skuList.push({
      attachment: {},
      state: 1,
      isMainChart: 0,
      purchaseUnitIndex: list[index].baseUnitIndex,
      baseUnitIndex: list[index].baseUnitIndex,
    });
    this.setData({
      ["alphaFormData.list"]: list,
    });
  },

  mainImageChange(e) {
    let { index, index2 } = e.currentTarget.dataset;
    let { value } = e.detail;
    let { field } = e.currentTarget.dataset;
    console.log("eeee", e);
    let list = this.data.alphaFormData.list;
    if (value) {
      list[index].skuList.forEach((v, k) => {
        if (k !== index2) {
          v.isMainChart = 0;
        }
      });
    } else {
      $wuxToast().show({
        type: "cancel",
        duration: 1000,
        color: "#fff",
        text: "至少保留一个主图",
        success: () => console.log("拦截提示"),
      });
      return;
    }

    this.setData({
      [`alphaFormData.list`]: list,
      [field]: e.detail.value ? 1 : 0,
    });
  },

  // // 重置
  // resetDto(){

  // },

  //基本单位变更，带动sku里面全部单位变更
  listBaseUnitChange(e) {
 
    this.setDataIndex(e);

    let list = this.data.alphaFormData.list;
    let { index } = e.currentTarget.dataset;
    if (
      list[index].confirmationCoefficientDtoList == undefined ||
      list[index].confirmationCoefficientDtoList.length <= 0
    ) {
      list[index].confirmationCoefficientDtoList = [
        {
          baseUnitIndex:list[index].baseUnitIndex,
          baseUnit: this.data.materialUnitList[list[index].baseUnitIndex].value,
          baseUnitName:
            this.data.materialUnitList[list[index].baseUnitIndex].label,
          purchasingUnit:
            this.data.materialUnitList[list[index].purchaseUnitIndex].value,
            purchasingUnitIndex:list[index].purchaseUnitIndex,
          purchasingUnitName:
            this.data.materialUnitList[list[index].purchaseUnitIndex].label,
          constId: "cg2ldbsxa2g0000",
          confirmationCoefficient: 1,
        },
      ];
    }
    list[index].skuList.forEach((v) => {
      v.purchaseUnitIndex = list[index].purchaseUnitIndex;
      v.baseUnitIndex = list[index].baseUnitIndex;
    });
    this.setData({
      [`alphaFormData.list`]: list,
    });
  },

  //sku采购价编辑，同时写入基础价格
  skuPriceComputedChange(e) {
    this.setDataIndex(e);
    this.computedPrice2(e);
  },

  computedPrice2(e) {
    let { index, index2 } = e.currentTarget.dataset;
    let sku = this.data.alphaFormData.list[index].skuList[index2];
    let confirmationCoefficient;
    this.data.alphaFormData.list[index].confirmationCoefficientDtoList.forEach(
      (v, k) => {
        if (
          v.purchasingUnitIndex == sku.purchaseUnitIndex &&
          v.baseUnitIndex == sku.baseUnitIndex
        ) {
          confirmationCoefficient = v.confirmationCoefficient;
        }
      }
    );
    if (confirmationCoefficient > 0) {
      sku.bigGoodsPrice = sku.plateCuttingPrice * confirmationCoefficient;
      this.setData({
        [`alphaFormData.list[${index}].skuList[${index2}]`]: sku,
      });
    }
  },

  //变更设置
  setDataIndex: function (e) {
    let { field } = e.currentTarget.dataset;
    // 是否选择了颜色 materialColorList  alphaFormData.list[0].skuList[0].colorCodeIndex
    console.log("field",field)
    console.log("value",e.detail.value)
    console.log("materialColorList",this.data.materialColorList)

    this.setData({
      [field]: e.detail.value,
    });
    console.log("alphaFormData",this.data.alphaFormData)

  },

  supplyCancelSelEvent(e) {
    let { selectedIndex } = e.detail;
    let list = this.data.alphaFormData.list;
    selectedIndex.forEach((index, k) => {
      let removeElement = list.splice(index, 1);
      this.data.supplyList.unshift({
        id: removeElement[0].supplierId,
        supplierShortName: removeElement[0].supplierShortName,
      });
    });
    this.setData({
      ["alphaFormData.list"]: list,
      supplyList: this.data.supplyList,
    });
    this.resetSupplyList();
  },

  //点击选择供应商
  supplySelEvent(e) {
    let sel_ids = e.detail.value;
    for (let index = 0; index < sel_ids.length; index++) {
      let findindex = this.data.supplyList.findIndex(
        (v) => v.id == sel_ids[index]
      );
      if (findindex != -1) {
        let findindex2 = this.data.alphaFormData.list.findIndex(
          (v) => v.id == sel_ids[index]
        );
        if (findindex2 == -1) {
          let is_sx = this.data.alphaFormData.list.findIndex(
            (v) => v.firstChooseIndex == 1
          );

          this.data.alphaFormData.list.push({
            supplierId: this.data.supplyList[findindex].id,
            supplierShortName:
              this.data.supplyList[findindex].supplierShortName,
            isEnableIndex: 0,
            firstChooseIndex: is_sx == -1 ? 1 : 0,
            skuList: [
              {
                attachment: {},
                state: 1,
                isMainChart: 1,

                /**示例数据 */
                // colorCodeIndex: 0,
                // supplierSpec: "我司规格/尺寸",
                // plateCuttingPrice: "1",
                // purchaseUnitIndex: 0,
                // bigGoodsPrice: 2,
                // baseUnitIndex: 1,
                // remark: "备注1123",
                /**示例数据 */
              },
            ],

            /**示例数据 */
            // supplierSpu: "面料款号111",
            // grossWidth: "11",
            // weight: "22",
            // spaceDifference: "33",
            // component: "44",
            // shrinkage: "55",
            // orderingCycle: "66",
            // productionCycle: "77",
            // remark: "备注111111",
            // baseUnitIndex: 0,
            /**示例数据 */
          });
        }
      }
    }
    this.setData({
      ["alphaFormData.list"]: this.data.alphaFormData.list,
    });
    this.resetSupplyList();
  },
  //资料页面切换
  navChange(e) {
    this.setData({
      current: e.detail.key,
    });
  },
  //供应商切换
  navSupplyChange(e) {
    console.log("eeee", e);
    this.setData({
      current_supplyid: e.detail.key,
    });
  },
  //重置供应商对应数据
  resetSupplyList() {
    for (let index = 0; index < this.data.alphaFormData.list.length; index++) {
      let useIndex = this.data.supplyList.findIndex(
        (v) => v.id == this.data.alphaFormData.list[index].supplierId
      );
      this.data.supplyList.splice(useIndex, 1);
    }

    // let use_ids = this.data.alphaFormData.list.map((v) => v.supplierId);

    this.setData({
      supplyList: this.data.supplyList,
      // sel_supply_ids: use_ids,
      current_supplyid:
        this.data.alphaFormData.list.map((v) => v.supplierId)[0] !== undefined
          ? this.data.alphaFormData.list.map((v) => v.supplierId)[0]
          : "",
    });
  },

  //供应商名称搜索框输入框内容变更
  search_keyword_change(e) {
    let { value } = e.detail;
    this.setData({
      search_keyword: value,
    });
    this.getSupplyList();
  },

  //获取供应商列表
  getSupplyList() {
    common
      .request_api(
        "/api/pdm/mdSupplier/getMdSupplierList",
        {
          current: 1,
          size: 100,
          selectParameter: {
            keyword: this.data.search_keyword,
            tabValue: "all",
          },
        },
        true,
        "post"
      )
      .then((res) => {
        this.setData({
          supplyList: res.data.records,
        });
        console.log("resres", res);
      });
  },

  //打开选择供应商窗口
  showSupplyEvent() {
    this.setData({
      isShowPopup: true,
    });
  },
  //关闭选择供应商窗口
  closeSupplyEvent() {
    this.setData({
      isShowPopup: false,
    });
  },

  //获取物料分类
  getMaterialCategoryTree() {
    common.request_api(
        "/api/pdm/commonDictionary/queryByGroupIdentification/materialType",
        {},
        true,
        "get"
    ).then((res) => {
        let materialCategoryTree = common.buildTree(res.data);
        let materialCategoryTreeIndexArr = [0, 0];
        let materialCategoryMeta = utils.opAefMetaCateMeta(
          materialCategoryTreeIndexArr,
          materialCategoryTree
        );
       
        this.setData({
          materialCategoryTree,
          materialCategoryTreeIndexArr,
          materialCategoryMeta,

          // 添加 bom 的分类
          abmMateCateMeta: materialCategoryMeta, 
          abmMateCateIdxArr:materialCategoryTreeIndexArr, 
        }); 
      });
  },

  //确定选择物料分类
  changeMaterialCategory(e) {
    var indexArr = e.detail.value;
    this.setData({
      materialCategoryTreeIndexArr: indexArr,
    });
  },

  //分类列改变
  colChangeMaterialCategory(e) {
    var materialCategoryTree = this.data.materialCategoryTree;
    var materialCategoryTreeIndexArr = this.data.materialCategoryTreeIndexArr;
    var index = e.detail.value;
    var column = e.detail.column;
    if (column == 0) {
      materialCategoryTreeIndexArr = [index, 0];
    }
    if (column == 1) {
      materialCategoryTreeIndexArr[1] = index;
    }
    let materialCategoryMeta = utils.opAefMetaCateMeta(
      materialCategoryTreeIndexArr,
      materialCategoryTree
    );
    this.setData({
      materialCategoryTreeIndexArr,
      materialCategoryMeta,
    });
  },

  //根据索引数组和树数据返回层级分类所需的元数据
  // getMeta(IndexArr, Tree) {
  //   let meta = [];
  //   let level = 1;
  //   for (let index = 0; index < IndexArr.length; index++) {
  //     if (level == 1) {
  //       meta[index] = Tree;
  //     } else if (level == 2) {
  //       meta[index] = Tree[IndexArr[index - 1]].children;
  //     } else if (level == 3) {
  //       meta[index] =
  //         Tree[IndexArr[index - 2]].children[IndexArr[index - 1]].children;
  //     }
  //     level++;
  //   }
  //   return meta;
  // },

  //获取物料详情
  getMaterialDetail() {
    common
      .request_api(
        "/api/pdm/materialMasterData/getMaterialMasterDataByPage",
        {
          selectParameter: { id: this.data.material_id },
        },
        true,
        "post"
      )
      .then((res) => {
        this.setData({
          alphaFormData: res.data,
          current_supplyid: res.data.list[0].supplierId,
        });
        this.setMetaDataIndex();
      });
  },

  /**************************************************************阿尔法*******************************************************/

   
 
  // 根据货号获取物料列表 物料档案 根据货号获取-打版任务列表，再次获取bom清单
  get_plate_tasts: function (productNo) {  
    console.log("根据货号获取物料列表",productNo)
      let that = this; 
      // 根据-aef接口
      // let str = '{"current":1,"size":10,"selectParameter":{"state":2,"orderLinkCode":"matchBom","componentsTemplateCode":"pdmPrintingTasks","confOrderCategory":"9","orderCode":"","productNo":"'+productNo+'","productGoods":"","confOrderTypeList":[],"designUserIdList":[],"supplierCodeList":[],"merchandiserIdList":[],"versionType":"","customerCodeList":[],"plateDeliveryDateStart":"","plateDeliveryDateEnd":"","productCategoryCodeList":"","isException":"","isTimeout":""}}';
      let str = '{"current":1,"size":10,"selectParameter":{"orderLinkCode":"matchBom","componentsTemplateCode":"pdmPrintingTasks","confOrderCategory":"9","orderCode":"","productNo":"'+productNo+'","productGoods":"","confOrderTypeList":[],"designUserIdList":[],"supplierCodeList":[],"merchandiserIdList":[],"versionType":"","customerCodeList":[],"plateDeliveryDateStart":"","plateDeliveryDateEnd":"","productCategoryCodeList":"","isException":"","isTimeout":""}}';
      // json 转 数组

      // 发起请求
      common.request_api (
          '/api/pdm/pdmPlateTask/queryPlateTaskPage',
          JSON.parse(str), 
          false
      ).then (res => {
          console.log("res",res)
          // 获取任务编号
          let orderCodes = res.data.records.map(order => order.orderCode);
          console.log("orderCodes",orderCodes)
          // that.setData ({
          //     batchList2:res.data.records
          // })
          // ZPM202501110002-0
          // orderCodes = ['ZPM202501110002-0','ZPM202501090001-0']
          // orderCodes.push('ZPM202501110002-0')
          // console.log("orderCodes-2",orderCodes)
          if(orderCodes.length<1) return true;
          common.request_api (
              '/api/pdm/pdmPlateTask/batchGetPlateTask',
              orderCodes, 
              false
          ).then (res => {
              console.log("batchGetPlateTask-res",res)
              // 组合数据  clothPrcinfoVo面料 .mdBomVo.colorInfs.fabricDetailBomVos.bomSizeDetailVos. materialName
              
              let plateTasts = [];
              res.data.forEach(plate => {
                  let plateBoms = []; 
                  console.log("fabricDetailBomVos-料",plate.mdBomVo.colorInfs)
                  // console.log("fabricDetailBomVos-面料2",plate.mdBomVo.colorInfs.fabricDetailBomVos)
              
                  plate.mdBomVo.colorInfs.forEach(plateBomItem => {
                      console.log('plateBomItem',plateBomItem); 
                        // 面料  
                        plateBomItem.fabricDetailBomVos.forEach(tItem => {
                          console.log('面料-tItem',tItem);  
                          plateBoms.push(tItem) 
                      });  
                      
                      // 辅料 
                      plateBomItem.accessoriesDetailBomVos.forEach(tItem => {
                          console.log('辅料-tItem',tItem);  
                          plateBoms.push(tItem) 
                      }); 
                      // 里料 
                      plateBomItem.liningDetailVos.forEach(tItem => {
                          console.log('里料-tItem',tItem);  
                          plateBoms.push(tItem) 
                      });  
                      // 公共耗材  
                      plateBomItem.commonConsumablesDetailVos.forEach(tItem => {
                          console.log('公共耗材-tItem',tItem);  
                          plateBoms.push(tItem) 
                      });  

                  }); 
                  plateTasts.push({
                      "orderCode":plate.orderCode,
                      "list":plateBoms,
                  })  
              });
              // plate_tasts
              console.log("plateTasts",plateTasts) 
              that.setData ({
                  plate_tasts: plateTasts
              })
          });  
      }); 
  },

  // 显示添加bom窗口
  onShowAddBom: function (e) {
    console.log("onShowAddBom-显示-添加bom窗口")
    this.setData({ 
      create_bom_show: true, 
    })
    console.log("create_bom_show",this.data.create_bom_show)
  },

  onHideAddBom: function (e) { 
    console.log("onHideAddBom-隐藏-添加bom窗口")
    this.setData({  
        create_bom_show: false, 
    })
  },

  getList(){
    if(this.data.lock===true){
      return;
    }
    if (this.data.material_id > 0) {
      this.getMaterialDetail();
    }

    this.getMaterialUnit();
    this.getMaterialColor();
    this.getMaterialCategoryTree();
  },

  // 预览图片
  PreViewImg: function (events) {
    var __this = this;
    // 数据下标
    var index = events.currentTarget.dataset.index;
    var path = events.currentTarget.dataset.path;
    var file_arr = [];
    // 取出所有图片的链接
    for (var i = 0; i < __this.data.tempFiles.length; i++) {
      file_arr.push(__this.data.tempFiles[i].tempFilePath);
    }
    // 调用
    wx.previewImage({
      current: path, // 当前显示图片的http链接
      urls: file_arr, // 需要预览的图片http链接列表
    });
  },
});
